package com.dingreading.cloud.soms.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.soms.dto.CmservicesDto;
import com.dingreading.cloud.soms.entity.Cmservices;
import com.dingreading.cloud.soms.entity.MemberTransfer;
import com.dingreading.cloud.soms.entity.Members;
import com.dingreading.cloud.soms.entity.Stores;
import com.dingreading.cloud.soms.service.*;
import com.dingreading.cloud.soms.util.LoginInfoUtil;
import com.dingreading.cloud.soms.util.redis.RedisService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/memberTransfer")
@Api(tags = "门店-会员转移管理")
public class FrontMemberTransferController {

    @Resource
    protected MembersService membersService;
    @Resource
    protected CmservicesService cmservicesService;
    @Resource
    protected StoresService storesService;
    @Resource
    protected MemberTransferService memberTransferService;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "申请门店uid") @RequestParam(value = "fromStoreUid", required = false) String fromStoreUid,
            @ApiParam(value = "目标门店uid") @RequestParam(value = "toStoreUid", required = false) String toStoreUid,
            @ApiParam(value = "会员名称/手机号") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "状态 0.待审核 1.通过 -1.拒绝") @RequestParam(value = "status", required = false) Integer status
    ) {
        if (StringUtils.isBlank(fromStoreUid) && StringUtils.isBlank(toStoreUid))
            return R.fail("未传递门店标识");

        Page<MemberTransfer> page = memberTransferService.pageList(pageUtil, corpUid, fromStoreUid, toStoreUid, keyword, status);

        PageBeanDto dto = new PageBeanDto();
        dto.setTotal(page.getTotalRow());
        dto.setList(page.getRecords());
        return R.ok(dto);
    }


    @ApiOperation(value = "获取会员可转移的服务")
    @PostMapping(value = "/getTransferServices", produces = "application/json; charset=UTF-8")
    public R<Object> getTransferServices(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid
    ) throws Exception {
        List<CmservicesDto> list = cmservicesService.getTransferServices(storeUid, memberUid);

        return R.ok(list);
    }


    @ApiOperation(value = "申请会员转移到其他门店")
    @PostMapping(value = "/applyMemberTransfer", produces = "application/json; charset=UTF-8")
    public R<Object> applyMemberTransfer(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "目标门店uid") @RequestParam(value = "toStoreUid") String toStoreUid,
            @ApiParam(value = "目标门店名称") @RequestParam(value = "toStoreName") String toStoreName,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "会员服务uid ['','']") @RequestParam(value = "serviceUids", required = false) String serviceUids,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark
    ) throws Exception {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();

        if (!AccountUtil.isStoreManager(loginDto.getStoreRoles()))
            return R.fail("非店长账号，不能操作");

        Stores stores = storesService.getByUid(storeUid);
        if (null == stores)
            return R.fail("门店获取失败");

        Members members = membersService.getByUid(storeUid, memberUid);
        if (null == members)
            return R.fail("未查询到该会员");
        if (members.getStoreUid().equals(toStoreUid))
            return R.fail("该会员已是目标门店的会员");

        boolean l = memberTransferService.haveMember(storeUid, memberUid);
        if (l)
            return R.fail("会员已申请门店转移，不能重复操作");

        // 判断目标门店下有相同手机号和姓名的会员
        Members exMember = membersService.haveCorpUidAndStoreUidAndMobAndFullName(stores.getCorpUid(), toStoreName, members.getMob(), members.getFullName());
        if (null != exMember) {
            if (null != exMember.getValidStatus() && exMember.getValidStatus().equals(1))
                return R.fail("手机号和姓名已被注册会员");
            else
                return R.fail("手机号和姓名已被注册线索");
        }

        String uids = "";
        String names = "";
        if (StringUtils.isNotBlank(serviceUids)) {
            List<String> serviceUidList = JSONArray.parseArray(serviceUids, String.class);
            if (CollectionUtils.isEmpty(serviceUidList))
                return R.fail("转移的服务信息解析失败，不能操作");
            List<Cmservices> serviceList = cmservicesService.listByStoreUidAndMemberUidAndUidIn(storeUid, memberUid, serviceUidList);
            if (CollectionUtils.isEmpty(serviceList))
                return R.fail("需要转移的服务获取失败");
            for (int i = 0; i < serviceList.size(); i++) {
                Cmservices data = serviceList.get(i);
                uids += data.getUid();
                if (data.getIsGift().equals(1))
                    names += "赠送-";
                names += data.getProductName() + "-" + data.getServiceDays() + "天";
                // 活动状态 1.可排活动 0.不可排活动
                if (data.getLessonStatus().equals(1)) {
                    if (data.getStatus().equals(EnumType.ServiceStatus.NO_CARD.getStatus())) {
                        names += "-" + data.getTotalLessons() + "次";
                    } else {
                        names += "-" + data.getLeftLessons() + "次";
                    }
                }
                names += "(" + EnumType.ServiceStatus.getStatus(data.getStatus()) + ")";
                if (i != serviceList.size() - 1) {
                    uids += ",";
                    names += ",";
                }
            }
        }

        MemberTransfer data = new MemberTransfer();
        data.setUid(KitUtil.getUuid());
        data.setMemberUid(memberUid);
        data.setFullName(members.getFullName());
        data.setMemberName(members.getMemberName());
        data.setMob(members.getMob());
        data.setCorpUid(stores.getCorpUid());
        data.setStoreUid(storeUid);
        data.setStaffUid(staffUid);
        data.setStaffName(staffName);
        data.setFromStoreUid(storeUid);
        data.setFromStoreName(stores.getStoreName());
        data.setToStoreUid(toStoreUid);
        data.setToStoreName(toStoreName);
        data.setServiceUids(uids);
        data.setServiceNames(names);
        data.setRemark(remark);
        data.setStatus(0);
        data.setAddStaffUid(staffUid);
        data.setAddStaffName(staffName);
        data.setLastStaffUid(staffUid);
        data.setLastStaffName(staffName);
        memberTransferService.saveOrUpdate(data);

        return R.ok();
    }


    @ApiOperation(value = "删除申请记录")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "申请uid") @RequestParam(value = "uid") String uid
    ) throws Exception {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();

        if (!AccountUtil.isStoreManager(loginDto.getStoreRoles()))
            return R.fail("非店长账号，不能操作");

        MemberTransfer data = memberTransferService.getByStoreUidAndUid(storeUid, uid);
        if (data == null) return R.fail("申请记录获取失败");

        if (!data.getStatus().equals(0))
            return R.fail("申请记录已审核，不能删除");

        long l = memberTransferService.dropBean(storeUid, uid);
        if (l <= 0)
            return R.failDel();

        return R.ok();
    }


    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "审核会员转移记录")
    @PostMapping(value = "/checkMemberTransfer", produces = "application/json; charset=UTF-8")
    public R<Object> checkMemberTransfer(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "申请uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "状态 0.待审核 1.通过 -1.拒绝") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "审核备注") @RequestParam(value = "checkRemark", required = false) String checkRemark
    ) throws Exception {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();
        long storeId = loginDto.getCurrentStoreId();

        if (!AccountUtil.isStoreManager(loginDto.getStoreRoles()))
            return R.fail("非店长账号，不能操作");

        MemberTransfer data = memberTransferService.getByToStoreUidAndUid(storeUid, uid);
        if (data == null) return R.fail("申请记录获取失败");

        if (!data.getStatus().equals(0))
            return R.fail("申请记录已审核，不能重复操作");

        List<String> uids = new ArrayList<>();
        if (StringUtils.isNotBlank(data.getServiceUids())) {
            uids = Arrays.stream(data.getServiceUids().split(",")).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(uids))
                return R.fail("转移的服务信息解析失败，不能操作");
        }

        boolean l = memberTransferService.updateStatus(storeUid, uid, status, staffUid, staffName, checkRemark);
        if (!l)
            return R.fail("审核失败");

        // 审核通过的操作
        if (status.equals(1)) {
            // 更新会员的门店信息
            l = membersService.updateStoreInfo(data.getFromStoreUid(), data.getMemberUid(), storeId, data.getToStoreUid(), data.getToStoreName());
            if (!l)
                throw new DescribeException("更新会员的门店信息失败");

            // 更新会员服务的门店信息
            if (CollectionUtils.isNotEmpty(uids)) {
                l = cmservicesService.updateStoreInfo(data.getFromStoreUid(), data.getMemberUid(), data.getToStoreUid(), data.getToStoreName(), uids);
                if (!l)
                    throw new DescribeException("更新会员服务的门店信息失败");
            }

            // 清空门店缓存数据
            redisService.setNullLike(RedisParam.STORE_MEMBERS + data.getFromStoreUid());
            redisService.setNullLike(RedisParam.STORE_MEMBERS + data.getToStoreUid());
        }
        return R.ok();
    }

}